package com.hanbang.qzzds.appliction.base.view.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.hanbang.qzzds.R;
import com.hanbang.qzzds.appliction.base.view.IActivityAndFragment;
import com.hanbang.qzzds.mode.httpresponse.BaseHttpResponse;
import com.hanbang.qzzds.mode.javabean.base.UserData;
import com.hanbang.qzzds.utils.other.ActivityUtils;
import com.hanbang.qzzds.utils.other.StringUtils;
import com.hanbang.qzzds.utils.ui.SnackbarUtil;
import com.hanbang.qzzds.utils.ui.SystemBarTintManager;
import com.hanbang.qzzds.utils.ui.ToastUtils;
import com.hanbang.qzzds.utils.ui.UiUtils;
import com.hanbang.qzzds.view.login.activity.LoginActivity;
import com.hanbang.qzzds.view.widget.appbarlayout.SupperToolBar;
import com.hanbang.qzzds.view.widget.dialog.DialogTransparency;
import com.hanbang.qzzds.view.widget.dialog.LoadDialog;
import com.hanbang.qzzds.view.widget.empty_layout.LoadingAndRetryManager;
import com.hanbang.qzzds.view.widget.empty_layout.MyOnLoadingAndRetryListener;
import com.hanbang.qzzds.view.widget.empty_layout.OnRetryClickListion;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * 作者　　: 李坤
 * 创建时间: 2016/9/19 17:12
 * <p>
 * 方法功能：
 * <p>
 * <p>
 * public static void startUI(Activity activity) {
 * Intent intent = new Intent(activity, HomeActivity.class);
 * intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
 * activity.startActivity(intent);
 * }
 */

public abstract class BaseActivity extends AppCompatActivity implements IActivityAndFragment {
    public int REQUEST_CODE = this.getClass().getSimpleName().hashCode() % 60000;
    /**
     * 订阅的集合，防止内存泄漏
     */
    private CompositeSubscription mCompositeSubscription;

    protected LoadingAndRetryManager loadingAndRetryManager = null;

    public SystemBarTintManager mTintManager;


    @Nullable
    @BindView(R.id.toolbar)
    protected SupperToolBar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTranslucentStatus(getStatusBarEnable(), getStatusBarResource());
        setContentView(getContentView());
        parseIntent(getIntent());
        initView();

    }


    public abstract void initView();

    public abstract void parseIntent(Intent intent);

    public abstract int getContentView();

    public int getStatusBarResource() {
        return R.color.main_black;
    }

    public int getStatusBarPaddingTop() {
        return UiUtils.getStatusHeight(this) - 2;
    }

    public boolean getStatusBarEnable() {
        return true;
    }

    /**
     * 显示不同的界面布局 监听器
     */
    public OnRetryClickListion getOnRetryClickListion() {
        if (this instanceof OnRetryClickListion) {
            return (OnRetryClickListion) this;
        } else {
            return null;
        }
    }

    //获取需要转化为loadingAndRetryManager的控件
    public View getSwitchRoot() {
        return findViewById(R.id.switchRoot);
    }

    public LoadingAndRetryManager getLoadingAndRetryManager() {
        return loadingAndRetryManager;
    }


    private void setTranslucentStatus(boolean on, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //状态栏透明 需要在创建SystemBarTintManager 之前调用。
            Window win = getWindow();
            WindowManager
                    .LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            if (on) {
                winParams.flags |= bits;
            } else {
                winParams.flags &= ~bits;
            }
            win.setAttributes(winParams);
            mTintManager = new SystemBarTintManager(this);
            mTintManager.setStatusBarTintEnabled(true);
            mTintManager.setNavigationBarTintEnabled(true);
            mTintManager.setTintResource(color);
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
        UiUtils.applyFont(UiUtils.getRootView(this));
        setRootViewPadding(getStatusBarPaddingTop());
        loadingAndRetryManager = LoadingAndRetryManager.getLoadingAndRetryManager(getSwitchRoot(), new MyOnLoadingAndRetryListener(this, getOnRetryClickListion()));
        if (toolbar != null) {

        }

    }

    public void setRootViewPadding(int top) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && getStatusBarEnable()) {
            UiUtils.getRootView(this).setPadding(0, top, 0, 0);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /**
         * 销毁网络访问的订阅
         */
        if (this.mCompositeSubscription != null) {
            this.mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        /**
         * 销毁网络访问的订阅
         */
        if (this.mCompositeSubscription != null) {
            this.mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    public boolean isLogin(boolean isToLogin) {
        if (UserData.isSLogin()) {
            if (isToLogin) {
                LoginActivity.startUI(this);
            }
            return false;
        } else {
            return true;
        }
    }


    public CompositeSubscription getCompositeSubscription() {
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }
        return this.mCompositeSubscription;
    }

    public void addSubscription(Subscription s) {
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }
        this.mCompositeSubscription.add(s);
    }


    /**
     * 显示对话框，用于网络请求
     *
     * @param msg
     * @param isCancelable
     */
    public void showDialog(String msg, boolean isCancelable) {
        if (loadDialog != null) {
            loadDialog.dismiss();
        }
        // 判断是否加载对话框
        if (!isFinishing()
                && ActivityUtils.isForeground(this)) {
            if (loadDialog == null) {
                loadDialog = new LoadDialog(this);
            }
            loadDialog.setContent(StringUtils.isNullToConvert(msg, getResources().getString(R.string.loadding)));
            loadDialog.setCancelable(isCancelable);
            try {
                loadDialog.show();
            } catch (Exception e) {

            }

        }
    }

    public void showDialog(String msg) {
        showDialog(msg, false);
    }

    public void showDialog() {
        showDialog(null);
    }

    public void dismissDialog() {
        if (loadDialog != null) {
            loadDialog.dismiss();
            loadDialog = null;
        }
    }

    public void httpError(String errString) {
        SnackbarUtil.showLong(this, errString, SnackbarUtil.Error).show();
    }

    public void showMessage(BaseHttpResponse result) {
        if (result != null) {
            SnackbarUtil.showLong(this, result.getMsg(), SnackbarUtil.Error).show();
        }
    }

    /**
     * 显示错误信息
     */
    public void showErrorMessage(String result) {
        if (result != null) {
            SnackbarUtil.showLong(this, result, SnackbarUtil.Error).show();
        }
    }

    public void showWarningMessage(String result) {
        if (result != null) {
            SnackbarUtil.showLong(this, result, SnackbarUtil.Warning).show();
        }
    }


    public void showMessageFinish(BaseHttpResponse result) {
        if (result.isSucceed()) {
            ToastUtils.showShort(this, result.getMsg());
        } else {
            SnackbarUtil.showLong(this, result.getMsg(), SnackbarUtil.Error).show();
        }
    }

    /**
     * 显示错误信息
     */
    public void showErrorSnackbar(String result) {
        showSnackbar(result, SnackbarUtil.Error, false);
    }

    public void showErrorSnackbar(String result, boolean isFinish) {
        showSnackbar(result, SnackbarUtil.Error, isFinish);
    }

    public void showWarningSnackbar(String result) {
        showSnackbar(result, SnackbarUtil.Warning, false);
    }

    public void showWarningSnackbar(String result, boolean isFinish) {
        showSnackbar(result, SnackbarUtil.Warning, isFinish);
    }

    public void showSnackbar(String result, int type, boolean isFinish) {

        if (result != null) {
            Snackbar snackbar = SnackbarUtil.showLong(this, result, type);

            if (isFinish) {
                final DialogTransparency dialog = new DialogTransparency(this);
                dialog.show();

                snackbar.setCallback(isFinish ? new Snackbar.Callback() {
                    @Override
                    public void onDismissed(Snackbar snackbar, int event) {
                        super.onDismissed(snackbar, event);
                        dialog.dismiss();

                        finish();
                    }

                } : null);
            }
            snackbar.show();
        }
    }

    /**
     * 用于显示提示
     */
    private LoadDialog loadDialog;

}
